const fs = require("fs");
const dir = require("../dir.js");
const log = require("../log.js");
const paramReplaceReg = /[\\/]{[^{}]+}/g;
const splitReg = /[\\/ _-]+[^\\/ _-]/;

function toCamel(str = ""){
  str = str.replace(/^[\\/]/, "").replace(/[\\/]+/, " ").replace(paramReplaceReg, "").replace(/{[^{}]+}/g, " ");
  while (splitReg.test(str)) {
    str = str.replace(splitReg, function () {
      return arguments[0][1].toUpperCase();
    })
  }
  return str;
}

module.exports = function (conf) {
  const list = dir.readFileInType(conf.inputPath, conf.fileReg);
  fs.writeFileSync(conf.outputPath, `export default {\n  ${list.filter(item => /\.[a-zA-Z]+$/.test(item.name)).map(item => {
    const [name, method, path] = item.name.split(/\./);
    const pathName = item.path.replace(/.+\/work-space-proxy\/proxy\/expresServer\/route/, "").replace(/(\.[a-zA-Z]+)*\.js$/,"");
    let urlName = pathName;
    while (/{([^{}]+)}/.test(urlName)) {
      urlName = urlName.replace(/{([^{}]+)}/, `/:$1/`)
    }
    const funcName = toCamel(pathName);
    return `${funcName.trim()}: {type: "${method}", url: "${urlName}"}`;
  }).join(",\n  ")}\n}`);
  log.t(`write ${conf.outputPath} success!`).end();
};
